#include <math/Rect.h>

namespace liba {
namespace math {

math::Rect<float> Transform(const math::Rect<float>& src, float z, const Matrix4<float>& m)
{
	math::Vector3<float> v[4];
	v[0] = math::Vector3<float>(src.x, src.y, z);
	v[1] = math::Vector3<float>(src.x + src.width, src.y, z);
	v[2] = math::Vector3<float>(src.x + src.width, src.y + src.height, z);
	v[3] = math::Vector3<float>(src.x, src.y + src.height, z);

	math::Vector3<float> tv[4];
	for (int i = 0; i < 4; ++i)
		tv[i] = m * v[i];

	math::Rect<float> result(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), 0, 0);
	for (int i = 0; i < 4; ++i)
	{
		if (tv[i].x < result.x)
			result. x = tv[i].x;
		if (tv[i].y < result.y)
			result.y = tv[i].y;
	}

	for (int i = 0; i < 4; ++i)
	{
		if (tv[i].x > result.x + result.width)
			result.width = tv[i].x - result.x;
		if (tv[i].y > result.y + result.height)
			result.height = tv[i].y - result.y;
	}

	return result;
}

} // namespace math
} // namespace liba